<template>
    <div>
        <div class="title">订单数:<em>{{totalCount}}</em>&nbsp;&nbsp;&nbsp;订单金额:<em>{{orderAmount}}</em></div>
        <div class="filter-btn">
            <el-col :span="24" class="toolbar">

                <div  style="display: flex">
                    <div style="width: 50%">
                        <el-select v-model="value1" placeholder="支付方式" @change="changePayType" style="width: 20%">
                            <el-option
                                    v-for="item in options"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                            </el-option>
                        </el-select>
                        <el-date-picker
                                v-model="value2"
                                type="datetimerange"
                                :picker-options="pickerOptions"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                align="right"
                                @change="changeTime"
                                value-format="yyyy-MM-dd">
                        </el-date-picker>
                    </div>
                    <div style="width: 50%;text-align: right">
                        <el-select v-model="value3" placeholder="商户选择" @change="changePayType" style="width: 20%">
                            <el-option
                                    v-for="item in merchs"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                            </el-option>
                        </el-select>
                        <el-input v-model="searchKey" placeholder="请输入关键字" style="width: 20%"></el-input>
                        <el-button type="primary" @click="_orderList">搜索</el-button>
                        <el-button style="background-color: rgb(26,179,148);color: #fff" @click="exportExcel">导出</el-button>
                    </div>
                </div>
            </el-col>
        </div>
        <el-table
                :data="tableData"
                style="width: 100%"
                stripe>
<!--            <el-table-column-->
<!--                    label="订单编号:"-->
<!--                    width="180">-->
<!--                <template slot-scope="scope">-->
<!--                    <span style="margin-left: 10px">{{ scope.row.ordersn }}</span>-->
<!--                </template>-->
<!--            </el-table-column>-->
            <el-table-column
                    label="活动详情"
                    width="300">
                <template slot-scope="scope">
                    <div style="display: flex;align-items: center">
                        <div><img :src="scope.row.banner" alt="" style="width: 50px;height: 50px;background-color:#ccc;"></div>
                        <div style="margin-left: 5px">
                            <span class="merch-name">{{ scope.row.merch_name}}</span>
                            <span style="background-color: #F56C6C;padding: 2px 4px;color: #fff;border-radius: 3px;font-size: 10px;margin-left: 1px" v-if="scope.row.optionid">{{ scope.row.option_title.replace(/\s*/g, '')}}</span>
                            <span class="merch-name" style="background-color:#ffc000;margin-left: 1px" v-if="scope.row.status === 1">等位中</span>
                            <br>
                            <span>{{ scope.row.title }}</span>
                        </div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column
                    label="单价"
                    width="150">
                <template slot-scope="scope">
                    <div class="content-title">
                        <span>{{ scope.row.price }}</span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column
                    label="会员信息"
                    width="150">
                <template slot-scope="scope">
                    <div class="content-title">
                        <span>{{ scope.row.nickname }}</span>
                        <span>{{ scope.row.babyname }}</span>
                        <span v-if="scope.row.mobile">{{scope.row.mobile.slice(0, 3) + '****' + scope.row.mobile.slice(scope.row.mobile.length-4)}}</span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column
                    label="支付方式"
                    width="150">
                <template slot-scope="scope">
                    <!--                    <span v-if="scope.row.paytype === 0" style="color: #1c84c6;">未支付</span>-->
                    <!--                    <span v-if="scope.row.paytype === 1" style="color: #1c84c6;">微信支付</span>-->
                    <!--                    <span v-if="scope.row.paytype === 2" style="color: #1c84c6;">支付宝支付</span>-->
                    <!--                    <span v-if="scope.row.paytype === 3" style="color: #1c84c6;">银联支付</span>-->
                    <span v-if="scope.row.paytype === 0" style="color: #fff;display: inline-block;background-color:#F56C6C;border-radius: 3px;font-size: 11px;padding: 0 3px"><i class="el-icon-warning"></i>未支付</span>
                    <span v-if="scope.row.paytype === 1" style="color: #fff;display: inline-block;background-color: #ffc000;border-radius: 3px;font-size: 11px;padding: 0 5px"><i class="fa fa-stop-circle"></i>{{ scope.row.paytype_text}}</span>
                    <span v-if="scope.row.paytype === 2" style="">{{ scope.row.paytype_text}}</span>
                    <span v-if="scope.row.paytype === 3" style="color: #fff;display: inline-block;background-color:#54c952;border-radius: 3px;font-size: 11px;padding: 0 3px"><i class="fa fa-weixin"></i>{{ scope.row.paytype_text}}</span>
                </template>
            </el-table-column>
<!--            <el-table-column-->
<!--                    label="价格"-->
<!--                    width="100">-->
<!--                <template slot-scope="scope">-->
<!--                    <span>{{ scope.row.price }}</span>-->
<!--                </template>-->
<!--            </el-table-column>-->
            <el-table-column
                    label="下单时间"
                    width="150">
                <template slot-scope="scope">
                    <p style="text-align: center">
                        <span>{{scope.row.create_time.split(' ')[0]}}</span><br>
                        <span>{{scope.row.create_time.split(' ')[1]}}</span>
                    </p>
                </template>
            </el-table-column>
            <el-table-column
                    label="状态"
                    width="150">
                <template slot-scope="scope">
                    <span v-if="scope.row.status === 0" style="color: #1c84c6;">待付款</span>
                    <span v-if="scope.row.status === 1" style="color: #1c84c6;">等位中</span>
                    <span v-if="scope.row.status === 2" style="color: #1c84c6;">待核销</span>
                    <span v-if="scope.row.status === 3" style="color: #1c84c6;">已完成</span>
                    <span v-if="scope.row.status === 4" style="color: #1c84c6;">已关闭</span>
<!--                    <el-button v-if="scope.row.refund_status !== 1" type="success" size="mini" @click="makeSureUse(scope.$index, scope.row)">确认使用</el-button>-->
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">查看详情</el-button>
                    <!--                        <el-button type="danger" size="mini" @click="handleDelete(scope.$index, scope.row)">关闭订单</el-button>-->
                    <el-button type="warning" size="mini" @click="handleRefund(scope.$index, scope.row)">处理退款</el-button>
                </template>
            </el-table-column>
        </el-table>


        <!-- 页码 -->
        <el-col :span="24" class="toolbar">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="pageSizes"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="totalCount">
            </el-pagination>
        </el-col>

        <!-- 查看详情dialog -->
        <el-dialog
                title="订单详情"
                :visible.sync="dialogVisible"
                width="60%">
            <el-steps :active="getState" align-center>
                <el-step title="会员下单" :description="currentOrder.create_time"></el-step>
                <el-step title="会员付款" :description="currentOrder.paytime"></el-step>
                <el-step title="确认使用" :description="currentOrder.verifytime"></el-step>
                <el-step title="订单完成" :description="currentOrder.finish_time"></el-step>
            </el-steps>


            <!--            订单信息这块-->
            <div class="order-info">
                <div class="detail-order" style="border-right: 1px solid #f2f2f2;width: 30%;padding-left: 10px;">
                    <div class="left-top">
                        <h2>订单信息</h2>
                        <p>订单编号：	{{currentOrder.ordersn}}</p>
                        <p>订单金额：	{{currentOrder.price}}</p>
                    </div>
                    <div class="left-bottom">
                        <p>核销方式：{{currentOrder.verifytype_text}}</p>
                        <p>消费码：{{currentOrder.address}}</p>
                        <p>会员：	<span style="color: #337ab7;">{{currentOrder.nickname}}</span></p>
                        <p>联系方式：{{currentOrder.mobile}}</p>
                    </div>
                </div>
                <div class="state-order">
                    <div class="right-top" style="height: 50%;padding-top: 10px;">
                        <span>订单状态:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<em style="font-style: normal;color: #999;font-size: 22px;font-weight: 600">{{currentOrder.status_text}}</em></span>
<!--                        <p style="padding-left: 85px;">会员已经付款</p>-->
                    </div>
                </div>
            </div>

            <!--            活动信息这块-->
            <div class="active-info">
                <h3 style="margin: 0;padding-bottom: 5px;">
                    活动信息
                </h3>
                <div class="active-bottom">
                    <div class="active-title">
                        <strong>标题</strong>
                        <strong>规格</strong>
                        <strong>价格</strong>
                        <strong>自定义</strong>
                    </div>
                    <div class="active-title-info">
                        <span style="color: #337ab7;cursor: pointer">{{ currentOrder.title }}</span>
                        <span>{{ currentOrder.optionid ? currentOrder.option_title.replace(/\s*/g, '') : '无' }}</span>
                        <span>{{ currentOrder.price }}</span>
                        <span> </span>
                    </div>
                </div>
            </div>


            <span slot="footer" class="dialog-footer">
<!--                <el-button @click="dialogVisible = false">取 消</el-button>-->
                <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
            </span>
        </el-dialog>

        <!--        关闭订单的dialog-->
        <el-dialog
                title="关闭订单"
                :visible.sync="dialogCloseOrder"
                width="40%">
            <el-input
                    type="textarea"
                    :rows="5"
                    placeholder="关闭订单原因"
                    v-model="textarea">
            </el-input>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogCloseOrder = false">取 消</el-button>
                <el-button type="primary" @click="makeSure">确 定</el-button>
            </span>
        </el-dialog>

<!--        退款的dialog-->
        <el-dialog
                title="提示"
                :visible.sync="dialogRefund"
                width="30%"
                @close="close">
            <el-tabs type="border-card">
                <el-tab-pane label="驳回">
                    <el-input
                            type="textarea"
                            :rows="2"
                            placeholder="请输入内容"
                            v-model="textareaContent">
                    </el-input>
                    <div style="text-align: center;margin-top: 10px;">
                        <el-button @click="dialogRefund = false">取 消</el-button>
                        <el-button type="primary" @click="rejectRefund">确 定</el-button>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="同意">
                    <el-radio v-model="radio" label="1">同意退款</el-radio>
<!--                    <el-radio v-model="radio" label="2">手动退款</el-radio>-->
                    <div style="text-align: center;margin-top: 10px;">
                        <el-button @click="dialogRefund = false">取 消</el-button>
                        <el-button type="primary" @click="agreeRefund">确 定</el-button>
                    </div>
                </el-tab-pane>
            </el-tabs>
<!--            <span slot="footer" class="dialog-footer">-->
<!--                <el-button @click="dialogRefund = false">取 消</el-button>-->
<!--                <el-button type="primary" @click="makeSureRefund">确 定</el-button>-->
<!--            </span>-->
        </el-dialog>

    </div>
</template>

<script>
    import { waitPayment, orderDetail, closeOrder, verifyOrder, refuseRefund, agree } from '../../api/order'
    import { merchkList } from '../../api/merchAPI'
    export default {
        name: "obligation",
        data() {
            return {
                options: [
                    {
                        value: '0',
                        label: '未支付'
                    },
                    {
                        value: '1',
                        label: '余额支付'
                    },
                    {
                        value: '2',
                        label: '支付宝支付'
                    }, {
                        value: '3',
                        label: '微信支付'
                    }
                ],
                form: {
                    paytype: '',
                    startTime: '',
                    endTime: '',
                    merch_id: ''
                },
                value1: '', // 支付方式绑定的值
                value2: '', // 日期选择绑定的值
                value3: '', // 商户选择
                pickerOptions: {
                    shortcuts: [{
                        text: '最近一周',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '最近一个月',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '最近三个月',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                            picker.$emit('pick', [start, end]);
                        }
                    }]
                },
                merchs: [], // 商户列表
                orderAmount: '', // 订单金额总的
                totalCount: 0, // 总共多少条
                pageSize: 10, // 每页显示条目个数
                pageSizes: [10, 20, 30, 40], // 每页显示个数选择器的选项设置
                currentPage: 1, // 当前页数
                tableData: [], // 订单数据列表
                dialogVisible: false, // 查看详情的控制器
                currentOrder: {}, // 当前点击的订单对象
                searchKey: '', // 搜索的关键字
                dialogCloseOrder: false, // 关闭订单的按钮
                textarea: '', // 关闭订单绑定的值
                userId2: '', // 点击关闭订单的时候的 对象
                dialogRefund: false, // 退款的dialog控制器
                radio: '1', // 同意退款的选择
                textareaContent: '', // 处理退款的 驳回内容
                refund: {} // 处理退款 当前点击的对象
            }
        },
        computed: {
            getState() {
                if (this.currentOrder.finish_time !== '') {
                    return 4
                } else if (this.currentOrder.verifytime !== '') {
                    return 3
                } else if (this.currentOrder.paytime !== '') {
                    return 2
                } else {
                    return 1
                }
            }
        },
        created() {
            this._orderList() // 获取订单列表
            this._merchkList() // 获取商户列表
        },
        methods: {
            // 导出数据
            exportExcel() {
                const apiUrl = "/admin/order/list"
                let param = new URLSearchParams();
                param.append("p", this.currentPage);
                param.append("length", 10000);
                param.append("keyword", this.searchKey);
                param.append("is_refund", 1);
                param.append("paytype", this.form.paytype);
                param.append("startTime", this.form.startTime);
                param.append("endTime", this.form.endTime);
                param.append("merch_id", this.form.merch_id);
                param.append("export", 1);
                this.$axios.post(apiUrl, param,{responseType: 'blob'}).then((res) => {
                    console.log( res.data)
                    const link = document.createElement('a')
                    let blob = new Blob([res.data],{type: 'application/vnd.ms-excel'});
                    link.style.display = 'none'
                    link.href = URL.createObjectURL(blob);
                    let num = ''
                    for(let i=0;i < 10;i++){
                        num += Math.ceil(Math.random() * 10)
                    }
                    link.setAttribute('download', '退款申请订单' + num + '.xlsx')
                    document.body.appendChild(link)
                    link.click()
                    document.body.removeChild(link)
                })
            },
            // 筛选支付方式
            changePayType(val) {
                console.log(val)
                this.form.paytype = val - 0
            },
            changeTime(val) {
                this.form.startTime = val[0]
                this.form.endTime = val[1]
            },
            _merchkList() {
                merchkList().then((res) => {
                    console.log(res)
                    this.merchs = res.data.merch
                }).catch(err => {
                    this.$message({
                        message: err.response.data.message,
                        type: 'error'
                    })
                })
            },
            // 刷新页面
            reloadPage() {
                // window.location.reload(); // 刷新当前页面
                location.reload();
            },
            // 确认使用
            makeSureUse(index, row) {
                console.log(index, row);
                this.$confirm('确认使用吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let data = { id: row.id }
                    verifyOrder(data).then(res => {
                        this.$message({
                            type: 'success',
                            message: '使用成功!'
                        });
                        this._orderList() // 重新订单列表
                    }).catch(err => {
                        this.$message({
                            message: err.response.data.message,
                            type: 'error'
                        })
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消'
                    });
                });
            },
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
                // 改变每页显示的条数
                this.pageSize = val;
                this._orderList()
                // 注意：在改变每页显示的条数时，要将页码显示到第一页
                this.currentPage = 1
            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.currentPage = val;
                this._orderList()
            },
            // 获取订单列表
            _orderList() {
                let params = {
                    p: this.currentPage, // 页码（默认1）
                    length: this.pageSize, // 每页数量（默认30）
                    keyword: this.searchKey, // 关键字
                    status: [], // 状态(0-待付款 1-已付款 2-待核销 3-已完成 4-已关闭)
                    is_refund: 1, // 查询退款订单（1-查询退款订单）
                    refund_status: '', // 退款状态(0-申请退款 1-退款完成 2-拒绝退款 3-用户取消)（is_refund=1的时候才生效）
                    mid: '', // 会员id
                    paytype: this.form.paytype, // 支付方式（0-未支付 1-余额支付 2-支付宝支付 3-微信支付）
                    startTime: this.form.startTime, // 开始时间
                    endTime: this.form.endTime, // 结束时间
                    merch_id: this.form.merch_id, // 商户id
                };
                waitPayment(params).then(res => {
                    console.log(res)
                    this.tableData = res.data.order
                    this.totalCount = res.data.total
                    this.orderAmount = res.data.orderAmount
                }).catch(err => {
                    this.$message({
                        message: err.response.data.message,
                        type: 'error'
                    })
                })
            },
            // 点击查看详情
            handleEdit(index, row) {
                this.dialogVisible = true
                let data = { id: row.id }
                orderDetail(data).then(res => {
                    console.log(res);
                    this.currentOrder = res.data.order
                }).catch(err => {
                    this.$message({
                        message: err.response.data.message,
                        type: 'error'
                    })
                })
            },
            // 点击关闭订单
            handleDelete(index, row) {
                console.log(index, row)
                this.userId2 = row
                if (row.status === 4) {
                    this.$message.success('订单已关闭，无需重复关闭');
                } else {
                    this.dialogCloseOrder = true
                }
            },
            // 关闭订单的确定按钮
            makeSure() {
                let data = { id: this.userId2.id,remark: this.textarea}
                closeOrder(data).then(res => {
                    this._orderList() // 重新订单列表
                    this.$message.success('关闭成功');
                    this.dialogCloseOrder = false
                    this.textarea = ''
                }).catch(err => {
                    this.$message({
                        message: err.response.data.message,
                        type: 'error'
                    })
                })
            },
            // 退款申请
            handleRefund(index, row) {
                console.log(index, row)
                this.refund = row
                this.dialogRefund = true
            },
            // 同意退款的 确认事件
            agreeRefund() {
                console.log(123)
                let data = { id: this.refund.id,type: this.radio - 0 }
                agree(data).then(res => {
                    this.$message.success('处理成功')
                    this.dialogRefund = false
                    this._orderList() // 获取订单列表
                }).catch(err => {
                    this.$message({
                        message: err.response.data.message,
                        type: 'error'
                    })
                })
            },
            // 驳回的确定 回调
            rejectRefund() {
                let data = { id: this.refund.id,remark: this.textareaContent }
                refuseRefund(data).then(res => {
                    this._orderList() // 获取订单列表
                    this.$message.success('驳回成功')
                    this.dialogRefund = false
                }).catch(err => {
                    this.$message({
                        message: err.response.data.message,
                        type: 'error'
                    })
                })
            },
            // 处理退款的dialog关闭的 回调
            close() {
                this.radio = '1'
                this.textareaContent = ''
            }


        }
    }
</script>

<style scoped>
    body {
        color: #676a6c;
    }
    .title {
        font-size: 16px;
        padding-bottom: 5px;
        border-bottom: 1px solid #ddd;
    }
    .title em {
        font-style: normal;
        color: red;
    }
    .filter-btn {
        display: flex;
    }
    .content-title {
        display: flex;
        flex-direction: column;
        text-align: center;
    }
    .order-info {
        display: flex;
        height: 280px;
        border: 1px solid #f2f2f2;
        margin-top: 10px;
    }
    .state-order {
        margin-left: 50px;
    }
    .active-info {
        margin-top: 10px;
        height: 160px;
        border: 1px solid #f2f2f2;
    }
    .active-title {
        display: flex;
        border-bottom: 1px solid #f2f2f2;
        padding-bottom: 5px;
    }
    .active-title-info {
        display: flex;
        padding-bottom: 5px;
    }
    .active-title strong,.active-title-info span {
        width: 25%;
    }
    .active-title-info span {
        line-height: 30px;
        padding-left: 5px;
    }
    .merch-name {
        background-color: #67C23A;
        padding: 2px 4px;
        color: #fff;
        border-radius: 3px;
        font-size: 10px
    }

</style>
